package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.entity.EventresultvehicleinfoEntity;
import com.tf.integrated.entity.SearchDataReturnEntity;
import com.tf.integrated.service.EventresultpedestriansinfoService;
import com.tf.integrated.service.EventresultvehicleinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Pattern;

/**
 * 车辆检索
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "车辆检索",description="SearchVehicleController")
@RestController
public class SearchVehicleController extends BaseController
{
    @Autowired
    private EventresultvehicleinfoService<EventresultvehicleinfoEntity> vehicleService;

    @ApiOperation("车辆检索")
    @GetMapping("/search/vehicles")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public SearchDataReturnEntity<JSONObject[]> searchDataList(@RequestParam Map<String, Object> data) {
        if (data != null && data.size() > 0) {
            String starttime=(String)data.get("starttime");
            String endtime=(String)data.get("endtime");
            String spage=(String)data.get("page");
            String ssize=(String)data.get("size");
            int page=0;
            int size=0;
            if(isExist(spage)&&isInteger(spage)){
                page=Integer.parseInt(spage);
            }
            if(isExist(ssize)&&isInteger(ssize)){
                size=Integer.parseInt(ssize);
            }
            int total=0;
            JSONObject[] arr=new JSONObject[0];
            if(isExist(starttime)&&isExist(endtime)&&page>=1&&size>0&&size<=200){
                int begin=(page-1)*size;
                int end=begin+size-1;
                EntityWrapperHandle<EventresultvehicleinfoEntity> ew = new EntityWrapperHandle<EventresultvehicleinfoEntity>();
                EntityWrapperHandle<EventresultvehicleinfoEntity> ew3 = new EntityWrapperHandle<EventresultvehicleinfoEntity>();
                ew.orderDesc(Collections.singletonList("id"));
                ew.last("limit "+(end+1));
                ew.between("createtime",starttime,endtime);
                ew3.between("createtime",starttime,endtime);
                String licence=(String)data.get("licence");
                if(isExist(licence)){
                    String sql=getSqlLicenceLike(licence);
                    ew.and(sql);
                    ew3.and(sql);
                }
                String[] hosts=getStringArray((String)data.get("host"));
                if(hosts.length>0){
                    String sql=getSqlAndEqualOr("deviceid",hosts);
                    ew.and(sql);
                    ew3.and(sql);
                }
                String[] chnIds=getStringArray((String)data.get("chnId"));
                if(chnIds.length>0){
                    String sql=getSqlAndEqualOr("chn",chnIds);
                    ew.and(sql);
                    ew3.and(sql);
                }
                String[] stylecode=getStringArray((String)data.get("stylecode"));
                if(stylecode.length>0){
                    String sql=getSqlAndEqualOr("code",stylecode);
                    ew.and(sql);
                    ew3.and(sql);
                }else{
                    String[] family=getStringArray((String)data.get("family"));
                    if(family.length>0){
                        String sql=getSqlAndEqualOr("family",family);
                        ew.and(sql);
                        ew3.and(sql);
                        String[] brand=getStringArray((String)data.get("brand"));
                        if(brand.length>0){
                            String sql2=getSqlAndEqualOr("brand",brand);
                            ew.and(sql2);
                            ew3.and(sql2);
                        }
                    }
                }
                Integer[] cartype=getIntArray((String)data.get("cartype"));
                if(cartype.length>0){
                    String sql= getJsonIdAndEqualOr("cartype",cartype);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] plateflag=getIntArray((String)data.get("plateflag"));
                if(plateflag.length>0){
                    String sql=getJsonTwoIdAndEqualOr("plateinfo","Flag",plateflag);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] platecolor=getIntArray((String)data.get("platecolor"));
                if(platecolor.length>0){
                    String sql=getJsonTwoIdAndEqualOr("plateinfo","Color",platecolor);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] platetype=getIntArray((String)data.get("platetype"));
                if(platetype.length>0){
                    String sql=getJsonTwoIdAndEqualOr("plateinfo","Type",platetype);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] color=getIntArray((String)data.get("color"));
                if(color.length>0){
                    String sql=getJsonIdAndEqualOr("color",color);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] markernum=getIntArray((String)data.get("markernum"));
                if(markernum.length>0){
                    String sql=getJsonIdAndEqualOr("markernum",markernum);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] paper=getIntArray((String)data.get("paper"));
                if(paper.length>0){
                    String sql=getJsonIdAndEqualOr("paper",paper);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] drop=getIntArray((String)data.get("drop"));
                if(drop.length>0){
                    String sql=getJsonIdAndEqualOr("`drop`",drop);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] codriver=getIntArray((String)data.get("codriver"));
                if(codriver.length>0){
                    String sql=getJsonIdAndEqualOr("codriver",codriver);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] mainnobelt=getIntArray((String)data.get("mainnobelt"));
                if(mainnobelt.length>0){
                    String sql=getJsonIdAndEqualOr("mainnobelt",mainnobelt);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] conobelt=getIntArray((String)data.get("conobelt"));
                if(conobelt.length>0){
                    String sql=getJsonIdAndEqualOr("conobelt",conobelt);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] hascall=getIntArray((String)data.get("hascall"));
                if(hascall.length>0){
                    String sql=getJsonIdAndEqualOr("hascall",hascall);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] hasrack=getIntArray((String)data.get("hasrack"));
                if(hasrack.length>0){
                    String sql=getJsonIdAndEqualOr("hasrack",hasrack);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] hassunroof=getIntArray((String)data.get("hassunroof"));
                if(hassunroof.length>0){
                    String sql=getJsonIdAndEqualOr("hassunroof",hassunroof);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] hassparetire=getIntArray((String)data.get("hassparetire"));
                if(hassparetire.length>0){
                    String sql=getJsonIdAndEqualOr("hassparetire",hassparetire);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] hascrash=getIntArray((String)data.get("hascrash"));
                if(hascrash.length>0){
                    String sql=getJsonIdAndEqualOr("hascrash",hascrash);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] isdanger=getIntArray((String)data.get("isdanger"));
                if(isdanger.length>0){
                    String sql=getJsonIdAndEqualOr("isdanger",isdanger);
                    ew.and(sql);
                    ew3.and(sql);
                }
                Integer[] isslag=getIntArray((String)data.get("isslag"));
                if(isslag.length>0){
                    String sql=getJsonIdAndEqualOr("isslag",isslag);
                    ew.and(sql);
                    ew3.and(sql);
                }
                List<EventresultvehicleinfoEntity> list = vehicleService.selectList(ew);
                total = vehicleService.selectCount(ew3);
                if(list!=null&&list.size()>0){
                    if (list.size() - 1 < begin) {
                        list.clear();
                    } else if (list.size() - 1 >= begin ) {
                        list=list.subList(begin,list.size());
                    }
                    arr=new JSONObject[list.size()];
                    for(int i=0;i<list.size();i++){
                        JSONObject json=new JSONObject();
                        json.put("id",list.get(i).getId());
                        json.put("CarType", list.get(i).getCartype());
                        json.put("Chn",list.get(i).getChn());
                        json.put("CoDriver",list.get(i).getCodriver());
                        json.put("CoNoBelt",list.get(i).getConobelt());
                        json.put("Color", list.get(i).getColor());
                        json.put("DriveWay",list.get(i).getDriveway());
                        json.put("Drop",list.get(i).getDrop());
                        json.put("FullPicPath",list.get(i).getFullpicpath());
                        json.put("HasCall",list.get(i).getHascall());
                        json.put("HasCrash",list.get(i).getHascrash());
                        json.put("HasRack",list.get(i).getHasrack());
                        json.put("HasSpareTire",list.get(i).getHassparetire());
                        json.put("HasSunroof",list.get(i).getHassunroof());
                        json.put("IsDanger", list.get(i).getIsdanger());
                        json.put("IsSlag",list.get(i).getIsslag());
                        json.put("MainNoBelt",list.get(i).getMainnobelt());
                        json.put("MarkerNum",list.get(i).getMarkernum());
                        json.put("ObjPicPath",list.get(i).getObjpicpath());
                        json.put("Orientation",list.get(i).getOrientation());
                        json.put("Paper",list.get(i).getPaper());
                        json.put("PlateInfo", list.get(i).getPlateinfo());
                        json.put("Rect",list.get(i).getRect());
                        json.put("StyleName",list.get(i).getStylename());
                        json.put("Time",list.get(i).getTime());
                        json.put("Type",list.get(i).getType());
                        json.put("DeviceId",list.get(i).getDeviceid());
                        arr[i]=json;
                    }
                }
            }
            return new SearchDataReturnEntity<JSONObject[]>().ok(arr,200,total);
        }
        return new SearchDataReturnEntity<JSONObject[]>().error("size or page err");
    }

    public boolean isExist(String value){
        return value != null && !value.equals("") ;
    }

    public String[] getStringArray(String s){
        if(isExist(s)){
            return s.split(",");
        }
        return new String[0];
    }

    public Integer[] getIntArray(String s){
        if(!isExist(s)){
            return new Integer[0];
        }
        String[] str = s.split(",");
        List<Integer> list = new ArrayList<>();
        for (String value : str) {
            if (isInteger(value)) {
                list.add(Integer.parseInt(value));
            }
        }
        return list.toArray(new Integer[0]);
    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public String getSqlAndEqualOr(String field,String[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append(field).append("='").append(values[i]).append("'");
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }

    public String getJsonTwoIdAndEqualOr(String field,String one,Integer[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append("JSON_EXTRACT(JSON_UNQUOTE(JSON_EXTRACT(").append(field).append(",'$.").append(one).append("')),'$.Id')=").append(values[i]);
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }

    public String getSqlLicenceLike(String licence){
        String lic=licence.replace("?","%");
        lic="%"+lic+"%";
        return "(JSON_UNQUOTE(JSON_EXTRACT(plateinfo,'$.Licence')) like '" + lic + "')";
    }

    public String getJsonIdAndEqualOr(String field,Integer[] values){
        StringBuilder sql= new StringBuilder();
        sql.append("(");
        for(int i=0;i<values.length;i++){
            sql.append("JSON_UNQUOTE(JSON_EXTRACT(").append(field).append(",'$.Id'))=").append(values[i]);
            if(i<values.length-1){
                sql.append(" or ");
            }else{
                sql.append(")");
            }
        }
        return sql.toString();
    }
}